import i18n from "./index"
import store from "@/store/index"
import { Loading } from "element-ui"
import zn from "@/lang/zn.js"
import en from "@/lang/en.js"
import { getI18n } from "@/api/language";

export function loadLanguageAsync() {
  const lang = store.getters.language
  i18n.locale = lang
  document.querySelector("html").setAttribute("lang", lang)
  return new Promise(async (resolve, reject) => {
    let loadingInstance = Loading.service({
      lock: true,
      text: lang == "zn" ? "加载中..." : "Loading...",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.4)",
      fullscreen: true
    })

    const local = lang == "zn" ? zn : en;
    // 从后端获取国际化配置
    const params = {
      language: lang === "zn" ? 1 : 0,  // 1:中文 0:英文
      terminalType: 0,  // 0:PC 1:App 2:Client
    };
    const res = await getI18n(params);
    // 合并国际化配置，后端返回的国际化配置优先级高于本地的
    const langConfig = _.merge({}, local, res?.data?.result?.['mes'] || {})
    i18n.setLocaleMessage(lang, langConfig);
    loadingInstance.close()
    resolve({ success: true, lang })
  })
}
